package com.dbsop.domain.transport.agg;

import com.dbsop.domain.transport.res.TransportUtils;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;

import java.util.List;

public final class TransportTermGroup extends TransportGroup {

    public TransportTermGroup(String fieldName) {
        super(fieldName);
    }

    public TransportTermGroup(String fieldName, String formatName) {
        super(fieldName, formatName);
    }


    @Override
    public AggregationBuilder aggregationBuilder() {
        TermsAggregationBuilder thisGroup =
                AggregationBuilders.terms(formatName).field(fieldName).size(this.size);

        if (group !=null)thisGroup.subAggregation(group.aggregationBuilder());

        if (aggOperations.size()>0){
            TransportUtils.paresAggregationBuilders(aggOperations)
                    .forEach(aggregationBuilder -> {
                        thisGroup.subAggregation(aggregationBuilder);
                    });
        }
        List<BucketOrder> order = order();
        if (order !=null) thisGroup.order(order);
        BucketOrder keyOrder = keyOrder();
        if (keyOrder !=null) thisGroup.order(keyOrder);
        return thisGroup;
    }

}
